<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Message Push Center</title>
    <!-- 引入 bootstrap.css -->
    <link rel="stylesheet" href="{{config('app.url')}}/asset/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="{{config('app.url')}}/asset/bootstrap/css/bootstrap-datetimepicker.min.css">
    <link rel="stylesheet" href="{{config('app.url')}}/asset/bootstrap/css/bootstrap-table.min.css">
    <link rel="stylesheet" href="{{config('app.url')}}/asset/bootstrap/css/bootstrap-switch.min.css">
    <!-- 引入 echarts.js -->
    <script src="{{config('app.url')}}/asset/echarts.min.js"></script>
    <!-- 引入 jquery.js -->
    <script src="{{config('app.url')}}/asset/jquery.min.js"></script>
    <!-- 引入 bootstrap.js -->
    <script src="{{config('app.url')}}/asset/bootstrap/js/bootstrap.min.js"></script>
    <script src="{{config('app.url')}}/asset/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
    <script src="{{config('app.url')}}/asset/bootstrap/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>
    <script src="{{config('app.url')}}/asset/bootstrap/js/bootstrap-table.min.js"></script>
    <script src="{{config('app.url')}}/asset/bootstrap/js/locales/bootstrap-table-zh-CN.js"></script>
    <script src="{{config('app.url')}}/asset/bootstrap/js/bootstrap-switch.min.js"></script>
    <!-- 引入 layer.js -->
    <script src="{{config('app.url')}}/asset/layer/layer.js"></script>
    <script src="{{config('app.url')}}/asset/md5.js"></script>
    <script src="{{config('app.url')}}/asset/functions.js"></script>
    <style type="text/css">.table {table-layout:fixed;word-break:break-all;}</style>
</head>
<body>

<input type="hidden" id="baseUrl" value="{{config('app.url')}}">
<div class="container_x" style="padding: 0px 50px">

    <h3>消息推送中心 -> 推送配置</h3>

    <div class="col-lg-12" style="margin-top: 20px;">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active"><a href="#set_sms" data-type="1">短信配置</a></li>
            <li><a href="#set_dingtalk" data-type="2">钉钉配置</a></li>
            <li><a href="#set_key" data-type="3">Key值管理</a></li>
            <li><a href="#set_queue" data-type="4">队列设置</a></li>
            <li><a href="#set_system" data-type="5">系统信息</a></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane active" id="set_sms">
                <button class="btn btn-sm btn-warning" style="margin-top: 15px"><span class="glyphicon glyphicon-plus" onclick="saveScene('sms')">添加</span></button>
                <table id="table-sms" class="table table-condensed"></table>
            </div>
            <div class="tab-pane" id="set_dingtalk">
                <button class="btn btn-sm btn-warning" style="margin-top: 15px"><span class="glyphicon glyphicon-plus" onclick="saveScene('dingtalk')">添加</span></button>
                <table id="table-dingtalk" class="table table-striped"></table>
            </div>
            <div class="tab-pane" id="set_key">
                <div class="text-muted" style="margin-top: 15px; margin-bottom: 10px;">&nbsp;Key值是什么
                    <span class="glyphicon glyphicon-question-sign layer_hover"
                          data-words="Key值是推送平台下开放接口的重要凭证，每次调用推送平台的接口都会验证Key值的合法性，若Key值被刷新，则对应的接口将会变得不可用，需谨慎操作。">
                    </span>
                </div>
                <table id="table-key" class="table table-hover"></table>
            </div>
            <div class="tab-pane" id="set_queue">
                <form action="#" style="margin-top: 20px;">
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="queue_name">队列名称：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span id="queue_name"></span>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="queue_exchange">交换机：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span id="queue_exchange"></span>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="queue_status">队列状态：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span id="queue_status">running...</span>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="queue_backhand">队列后台：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <a href="#" target="_blank"  id="queue_backhand"></a>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">重启队列：</label>
                        </div>
                        <div class="form-group col-md-6" style="margin-top: -6px;">
                            <span class="btn btn-danger btn-sm" onclick="restartQueue()">重启</span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="tab-pane" id="set_system">
                <form action="#" style="margin-top: 20px;">
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">系统名称：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span id="system_name"></span>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">系统状态：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span  id="system_status"></span>
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">支持平台：</label>
                        </div>
                        <div class="col-md-11 form-group" style="margin-top: -6px;" id="platform">
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">支持渠道：</label>
                        </div>
                        <div class="col-md-11 form-group" style="margin-top: -6px;" id="channel">
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">钉钉消息：</label>
                        </div>
                        <div class="col-md-11 form-group" style="margin-top: -6px;" id="dingtalk_type">
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">短信消息：</label>
                        </div>
                        <div class="col-md-11 form-group" style="margin-top: -6px;" id="sms_type">
                        </div>
                    </div>
                    <div class="row form-row">
                        <div class="col-md-1 form-group">
                            <label for="scene_name">系统版本：</label>
                        </div>
                        <div class="col-md-6 form-group">
                            <span id="system_version"></span>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <div style="display: none; padding: 10px;" id="edit_scene">
        <form action="#">
            <div class="form-row">
                <div class="col-md-6 form-group">
                    <label for="platform_id">关联平台</label>
                    <select class="form-control" id="platform_id">
                        <option value="">请选择平台</option>
                    </select>
                </div>
                <div class="col-md-6 form-group">
                    <label for="channel_id">关联渠道</label>
                    <select class="form-control" id="channel_id">
                        <option value="">请选择渠道</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="col-md-6 form-group">
                    <label for="msg_type">消息类型</label>
                    <select class="form-control" id="msg_type">
                        <option value="">请选择消息类型</option>
                    </select>
                </div>
                <div class="col-md-6 form-group" id="scene_body_show">
                    <label for="scene_body">重要参数</label>
                    <input type="text" class="form-control" id="scene_body" />
                </div>
            </div>

            <div class="form-row">
                <div class="col-md-12 form-group">
                    <label for="scene_name">场景名称</label>
                    <input type="text" class="form-control" id="scene_name" placeholder="场景名称">
                </div>
            </div>

            <div class="form-row">
                <div class="col-md-12 form-group">
                    <label for="remark">备注</label>
                    <input type="text" class="form-control" id="remark" placeholder="备注">
                </div>
            </div>

            <div class="form-row" id="scene_status_show">
                <div class="col-md-12 form-group">
                    <label for="scene_status" style="margin-right: 10px;">启用状态</label>
                    <input type="checkbox" class="form-control" id="scene_status" checked />
                </div>
            </div>

        </form>
    </div>

</div>

<script type="text/javascript">

    let baseUrl = $('#baseUrl').val();

    $(function () {

        // 初始化列表数据
        let table = $('#table-sms');
        initTable(table, 'sms');
        // 点击搜索请求数据列表
        $("#btn_query").on('click', function () {
            //点击查询是 使用刷新 处理刷新参数
            table.bootstrapTable('refresh');
        });
        let table2 = $('#table-dingtalk');
        let table3 = $('#table-key');

        // 选项卡切换
        $('#myTab a:first').tab('show');
        $('#myTab a').click(function (e) {
            let tabType = $(this).data('type');
            if (tabType === 1) {
                initTable(table, 'sms');
            }
            if (tabType === 2) {
                initTable(table2, 'dingtalk');
            }
            if (tabType === 3) {
                initTable(table3, 'key');
            }
            if (tabType === 4) {
                initQueue();
            }
            if (tabType === 5) {
                initSystem();
            }
            e.preventDefault();
            $(this).tab('show');
        });

        // 开关控件
        $("#scene_status").bootstrapSwitch({
            onText : "ON",        // 设置ON文本
            offText : "OFF",      // 设置OFF文本
            onColor : "success",  // 设置ON文本颜色           (info/success/warning/danger/primary)
            offColor : "danger",  // 设置OFF文本颜色          (info/success/warning/danger/primary)
            size : "small",       // 设置控件大小,从小到大     (mini/small/normal/large)
            // 当开关状态改变时触发
            onSwitchChange : function(event, state) {
                if (state === true) {
                    //alert("ON");
                } else {
                    //alert("OFF");
                }
            }
        });

        // layer 悬停
        let tip_index = 0;
        $(document).on('mouseenter', '.layer_hover', function(){
            let words = $(this).data('words');
            tip_index = layer.tips(words, '.layer_hover', {time: 0, area: ['1000'],});
        }).on('mouseleave', '.layer_hover', function(){
            layer.close(tip_index);
        });

    });

    // 初始化表格数据
    function initTable(table, type) {
        let typeColumn = [];
        if (type === 'key') {
            typeColumn = [ // 列详情
                {
                    title: 'ID',// 表头字段名
                    field: 'id',// 数据 key
                    sortable: true,// 排序
                    align: 'center',// 居中
                    width:  80,
                    visible: true
                }, {
                    title: '推送场景',
                    field: 'name',
                    width:  400,
                    align: 'center'
                }, {
                    title: 'Key值',
                    field: 'key',
                    width:  300,
                    align: 'center'
                }, {
                    title: '更新时间',
                    field: 'update_time',
                    formatter: function (value, row, index) {
                        return datetimeFormat(value)
                    },
                    width:  150,
                    align: 'center'
                }, {
                    field: '',
                    title: '管理',
                    align: 'center',
                    width:  120,
                    formatter: function (value, row, index) {
                        return '<button class="btn btn-xs btn-success" onclick="refreshSceneKey(' + row.id + ')">刷新Key</button>&nbsp;&nbsp;';
                    }
                }
            ];
        } else {
            typeColumn = [ // 列详情
                {
                    title: 'ID',// 表头字段名
                    field: 'id',// 数据 key
                    sortable: true,// 排序
                    align: 'center',// 居中
                    width:  80,
                    visible: true
                }, {
                    title: '推送场景',
                    field: 'name',
                    width:  400,
                    align: 'center'
                }, {
                    title: '关联平台',
                    field: 'platform.name',
                    align: 'center'
                }, {
                    title: '消息类型',
                    field: 'msg_type_name',
                    width:  80,
                    align: 'center'
                }, {
                    title: '启用状态',
                    field: 'status',
                    formatter: function (value, row, index) {
                        return value === 1 ? "启用中" : "已停用";
                    },
                    align: 'center'
                }, {
                    title: '备注',
                    field: 'remark',
                    align: 'center',
                }, {
                    title: '创建时间',
                    field: 'create_time',
                    formatter: function (value, row, index) {
                        return datetimeFormat(value)
                    },
                    width:  150,
                    align: 'center'
                }, {
                    field: '',
                    title: '管理',
                    align: 'center',
                    width:  120,
                    formatter: function (value, row, index) {
                        let title = '';
                        let className = '';
                        if (row.status) {
                            title = '停用';
                            className = 'btn-danger';
                        } else {
                            title = '启用';
                            className = 'btn-success';
                        }
                        let param = "'" + type + "', '" + encodeURIComponent(JSON.stringify(row)) + "'";
                        let paramOff = "'" + type + "', '" + row.id + "', '" + row.status + "'";
                        let toolbar = '<button class="btn btn-xs btn-default" onclick="saveScene(' + param + ')" title="修改"><span class="glyphicon glyphicon-pencil"></button>&nbsp;&nbsp;';
                            toolbar += '<button class="btn btn-xs ' + className + '" onclick="offScene(' + paramOff + ')" title="' + title + '"><span class="glyphicon glyphicon-off"></button>&nbsp;&nbsp;';
                            //toolbar += '<button class="btn btn-xs btn-danger"onclick="deleteScene(this)" title="删除"><span class="glyphicon glyphicon-trash"></button>';
                        return toolbar;
                    }
                }
            ];
        }
        // 先销毁再创建
        table.bootstrapTable('destroy').bootstrapTable({
            //data: data, // 本地数据列表
            url: baseUrl + "/api/setting/" + type,
            method: 'post',
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            classes: 'table table-bordered table-hover table-striped', // 样式，table-striped 隔行变色
            pagination: true,//是否分页
            pageNumber : 1, //初始化加载第一页
            pageSize: 10,//单页记录数
            pageList: [5, 10, 15, 20],//分页步进值
            sidePagination: "server",//服务端分页
            //search: true,//本地数据表格搜索，配合data使用
            //showRefresh: true,//刷新按钮
            //showColumns: true,//列选择按钮
            toolbar: '#toolbar',
            queryParamsType: "limit",//查询参数组织方式
            queryParams : function(params) {//上传服务器的参数
                params.scene_type = type;
                return getSearchParams(params);
            },
            columns: typeColumn
        });
    }

    // 获取搜索数据
    function getSearchParams(params) {
        // 默认参数
        params.page = (params.offset / params.limit) + 1; //当前页码
        // 接收参数
        // 生成签名
        params = getSign(params, 'pages/setting');
        return params;
    }

    // 保存场景
    function saveScene(type, data = '0') {
        let id = 0;
        initType(type);
        if (type !== 'sms') {
            $('#scene_body_show,#scene_status_show').hide();
        } else {
            $('#scene_body_show,#scene_status_show').show();
        }
        if (data === '0') {
            // 添加
            $('#scene_status_show').show();
            $('#platform_id,#channel_id,#msg_type,#scene_body,#scene_name,#remark').val('');
            $('#platform_id,#channel_id').attr("disabled", false);
            $('#scene_status').bootstrapSwitch('state', true);
        } else {
            // 编辑
            data = JSON.parse(decodeURIComponent(data));
            id = data.id;
            $('#scene_status_show').hide();
            setTimeout(function () {
                $('#platform_id option[value="' + data.platform_id + '"]').attr("selected", true);
                //$('#platform_id').val(data.platform_id).attr("disabled", true);
                $('#platform_id').val(data.platform_id);
                $('#channel_id option[value="' + data.channel_id + '"]').attr("selected", true);
                $('#channel_id').val(data.channel_id).attr("disabled", true);
                $('#msg_type option[value="' + data.msg_type + '"]').attr("selected", true);
                $('#msg_type').val(data.msg_type);
            }, 700)
            $('#scene_name').val(data.name);
            $('#scene_body').val(data.body);
            $('#remark').val(data.remark);
        }
        layer.open({
            type: 1,
            title: "添加/编辑",
            content: $('#edit_scene')
            ,area: ['500px', '500px']
            ,btn: ['确定', '取消']
            ,btnAlign: 'c'
            ,yes: function (index) {
                let params = {
                    scene_id : id,
                    scene_type: type,
                    platform_id: $('#platform_id').val(),
                    scene_name: $('#scene_name').val(),
                    msg_type: $('#msg_type').val(),
                    body: $('#scene_body').val(),
                    remark: $('#remark').val(),
                };
                if (id === 0) {
                    params.channel_id = $('#channel_id').val();
                    params.platform_id = $('#platform_id').val();
                    params.status = $('#scene_status').bootstrapSwitch('state') ? 1 : 0;
                    if (params.channel_id === '') {
                        layer.msg('请选择渠道');
                        return false;
                    }
                }
                if (params.platform_id === '') {
                    layer.msg('请选择平台');
                    return false;
                }
                $.ajax({
                    url: baseUrl + '/api/setting/save',
                    method: 'post',
                    data: getSign(params, 'api/setting'),
                    success: function (res) {
                        if (res.status === 'success') {
                            $('#table-' + type).bootstrapTable('refresh');
                        }
                        layer.close(index);
                        layer.msg(res.msg);
                    },
                    error: function (res) {
                        layer.close(index);
                        layer.msg('服务器错误，请重试');
                        console.log(res.responseText)
                    }
                });
                return true;
            }
        });
        return true;
    }

    // 关闭/启用场景
    function offScene(type, id = '0', status = '0') {
        if (!id) {
            layer.msg('ID不能为空');
            return false;
        }
        let msg = status === '0' ? '确定开启吗？开启后恢复消息推送' : '确定停用吗？停用后该场景下的所有消息将不再推送！';
        layer.confirm(msg, {
            btn: ['确定', '取消']
            ,yes: function (index) {
                let params = {
                    scene_id : id,
                    scene_type: type,
                    status: status === '0' ? 1 : 0
                };
                $.ajax({
                    url: baseUrl + '/api/setting/offScene',
                    method: 'post',
                    data: getSign(params, 'api/setting'),
                    success: function (res) {
                        if (res.status === 'success') {
                            $('#table-' + type).bootstrapTable('refresh');
                        }
                        layer.close(index);
                        layer.msg(res.msg);
                    },
                    error: function (res) {
                        layer.close(index);
                        layer.msg('服务器错误，请重试');
                        console.log(res.responseText)
                    }
                });
                return true;
            }
        });
        return true;
    }

    // 刷新key
    function refreshSceneKey(id = 0) {
        if (!id) {
            layer.msg('ID不能为空');
            return false;
        }
        layer.confirm("注意：刷新Key值后，原开放接口将不可用，请谨慎操作！", {
            btn: ['确定', '取消']
            ,yes: function (index) {
                let params = {
                    scene_id: id,
                    scene_type: 'key',
                    refresh_key: 1,
                };
                $.ajax({
                    url: baseUrl + '/api/setting/refreshKey',
                    method: 'post',
                    data: getSign(params, 'api/setting'),
                    success: function (res) {
                        if (res.status === 'success') {
                            $('#table-key').bootstrapTable('refresh');
                        }
                        layer.msg(res.msg);
                    },
                    error: function (res) {
                        layer.close(index);
                        layer.msg('服务器错误，请重试');
                        console.log(res.responseText)
                    }
                });
                return true;
            }
        });
        return true;
    }

    // 重启队列
    function restartQueue()
    {
        let params = {};
        $.ajax({
            url: baseUrl + '/api/setting/queue/reload',
            method: 'post',
            data: getSign(params, 'api/setting'),
            success: function (res) {
                if (res.status === 'success') {
                    $('#queue_status').html('restarting...');
                }
                layer.msg(res.msg);
            },
            error: function (res) {
                layer.close(index);
                layer.msg('服务器错误，请重试');
                console.log(res.responseText)
            }
        });
        return false;
    }

    // 初始化类型
    function initType(type)
    {
        let params = {
            scene_type: type
        };
        $.ajax({
            url: baseUrl + '/api/setting/' + type + '/type',
            method: 'post',
            data: getSign(params, 'api/setting'),
            success: function (res) {
                if (res.status === 'success') {
                    initSelect('#msg_type', res.result.msg_type, '<option value="">请选择消息类型</option>');
                    initSelect('#channel_id', res.result.channel, '<option value="">请选择渠道</option>');
                    initSelect('#platform_id', res.result.platform, '<option value="">请选择平台</option>');
                }
                //layer.msg(res.msg);
            },
            error: function (res) {
                layer.close(index);
                layer.msg('服务器错误，请重试');
                console.log(res.responseText)
            }
        });
        return false;
    }

    // 初始化 select
    function initSelect(id, list, emptyStr = '') {
        let option = emptyStr;
        for (let i in list) {
            option += "<option value='" + list[i].id + "'>" + list[i].name + "</option>";
        }
        $(id).html(option);
        return true;
    }

    // 初始化 div
    function initDiv(id, list, className = 'btn-default') {
        let option = '';
        for (let i in list) {
            option += "<span class='btn btn-sm " + className + "' style='margin-bottom: 7px;' data-id='" + list[i].id + "'>" + list[i].name + "</span>&nbsp;&nbsp;";
        }
        $(id).html(option);
        return true;
    }

    // 初始化类型
    function initQueue()
    {
        let params = {};
        $.ajax({
            url: baseUrl + '/api/setting/queue',
            method: 'post',
            data: getSign(params, 'api/setting'),
            success: function (res) {
                if (res.status === 'success') {
                    $('#queue_name').html(res.result.queue_name);
                    $('#queue_exchange').html(res.result.queue_exchange);
                    $('#queue_status').html(res.result.queue_status);
                    $('#queue_backhand').html(res.result.queue_backhand).attr('href', res.result.queue_backhand);
                }
                //layer.msg(res.msg);
            },
            error: function (res) {
                layer.close(index);
                layer.msg('服务器错误，请重试');
                console.log(res.responseText)
            }
        });
        return false;
    }

    // 初始化系统信息
    function initSystem()
    {
        let params = {};
        $.ajax({
            url: baseUrl + '/api/setting/info',
            method: 'post',
            data: getSign(params, 'api/setting'),
            success: function (res) {
                if (res.status === 'success') {
                    $('#system_name').html(res.result.system_name);
                    $('#system_status').html(res.result.system_status);
                    $('#system_version').html(res.result.system_version);
                    initDiv('#platform', res.result.platform, 'btn-warning');
                    initDiv('#channel', res.result.channel, 'btn-success');
                    initDiv('#dingtalk_type', res.result.dingtalk_type, 'btn-info');
                    initDiv('#sms_type', res.result.sms_type, 'btn-primary');
                }
                //layer.msg(res.msg);
            },
            error: function (res) {
                layer.close(index);
                layer.msg('服务器错误，请重试');
                console.log(res.responseText)
            }
        });
        return false;
    }

</script>
</body>
</html>